/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: htang
 * @Date: 2024-01-15 15:39:57
 * @LastEditors: htang
 * @LastEditTime: 2024-05-29 12:12:39
 */
import { defHttp } from '/@/utils/http/axios';
import { createVNode } from 'vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import { getCameraInfo } from '/@/utils/auth';
import { encryptByMd5 } from '/@/utils/cipher.ts';
import { useUserStoreWithOut } from '/@/store/modules/user';
import moment from 'moment';

const TOKEN = getCameraInfo()?.accessToken

const ROOT_API = 'http://27.45.145.110:27078/api'; //import.meta.env.VITE_GLOB_API_CAMERA_URL;

const API = {
  // 登录接口
  login: `${ROOT_API}/user/login`,
  // 登出接口
  logout: `${ROOT_API}/user/logout`,
  // 设备地址
  devices: `${ROOT_API}/device/query/devices`,
  // 获取设备摄像头
  tree: `${ROOT_API}/device/query/tree`,
  // 播放视频地址
  playStart: `${ROOT_API}/play/start/`,
  // 时间列表
  dateList: `${ROOT_API}/cloud/record/date/list`,
  playStop: `${ROOT_API}/play/stop/`,
  // 停止推流 deviceId channelId streamId
  playBackStop: `${ROOT_API}/playback/stop/`,
  // 视频回放
  playBack: `${ROOT_API}/playback/start/`,
  // 获取回放时间段
  gbRecordQuery: `${ROOT_API}/gb_record/query/`,
  // 码流设置
  identificationUpdate: `${ROOT_API}/device/query/channel/stream/identification/update/`
}

/**
 * 登录摄像头获取token数据
 * @param params
 * @returns
 */
export const cameraSystemLogin = async (params) => {
  return new Promise((resolve, reject) => {
    $.get(API.login, params, ({ data }) => {
      resolve(data);
    })
  })
}

/**
 * 刷新token
 */
function refreshToken() {
  // 实现 token 刷新的逻辑
  return new Promise((resolve, reject) => {
    $.ajax({
      url: API.login,
      data: {
        username: "admin",
        password: encryptByMd5("admin"),
      },
      success: (res) => {
        const userStore = useUserStoreWithOut();
        let { data, code } = res;
        if (code == 0) {
          let info = data;
          info['dateTime'] = moment().valueOf();
          // 存储新的 token
          localStorage.setItem('water-camera-token', info.accessToken);
          userStore.setCameraData(info);
          resolve(data);
        } else {
          reject(res);
        }
      },
      error(err) {
        console.log(err)
        reject(err);
      },
    });
  });
}

/**
 * token检测
 * @param options
 * @returns
 */
function requestWithTokenCheck(options: any) {
  return new Promise((resolve, reject) => {
    $.ajax({
      ...options,
      success: (res) => {
        // 如果不是因为 token 过期，直接返回结果
        resolve(res);
      },
      error: (err, textStatus, errorThrown) => {
        // 检查是否因为 token 过期导致请求失败，这里以状态码 401 为例
        if (err.status == 401) {
          // 尝试刷新 token
          refreshToken().then(v => {
            let newToken = v.accessToken;
            // 使用新 token 重新设置请求头
            options.headers = options.header || {};
            options.headers['Access-Token'] = newToken;
            options.headers['Content-Type'] = `application/json`;
            // 重新发送请求
            $.ajax({
              ...options,
              success: (v) => {
                resolve(v);
              },
              fail: (err) => {
                reject(err);
              }
            });
          }).catch((err) => {
            // 处理无法刷新 token 的情况，比如跳转到登录页面
            reject(new Error('Unable to refresh token'));
          });
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 获取视频流数据
 * @param {int} page 当前页
 * @param {int} count 当前页总数
 * @returns
 */
export const deviceQueryApi = async (data) => {
  let params = data;
  return new Promise((resolve, reject) => {
    requestWithTokenCheck({
      url: API.devices,
      data: params,
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      resolve(res.data);
    })
  })
}

/**
 * 获取视频流数据
 * @param {int} page 当前页
 * @param {int} count 当前页总数
 * @returns
 */
export const queryChannelsApi = async (deviceId, params) => {
  return new Promise((resolve, reject) => {
    requestWithTokenCheck({
      url: `${API.devices}/${deviceId}/channels`,
      data: params,
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      resolve(res.data);
    })
  })
}

/**
 * 获取视频回放列表数据
 * @param {int} page 当前页
 * @param {int} count 当前页总数
 * @returns
 */
export const deviceQueryBackApi = async (data) => {
  let { deviceId } = data;
  return new Promise((resolve, reject) => {
    requestWithTokenCheck({
      url: `${API.devices}/${deviceId}`,
      data: {},
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      resolve(res.data);
    })
  })
}

/**
 * 获取设备下的摄像抢数据
 * @param {int} page 当前页
 * @param {int} count 当前页总数
 * @param {int} parentId 父ID
 * @returns
 */
export const deviceQueryTeeApi = async (parentId, params) => {
  return new Promise((resolve, reject) => {
    requestWithTokenCheck({
      url: `${API.tree}/${parentId}`,
      data: params,
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      resolve(res.data);
    })
  })
}

/**
 * 设备摄像头播放
 * @param deviceId
 * @param channelId
 * @returns
 */
export const deviceCameraPlayApi = async (data) => {
  let { deviceId, channelId } = data;
  return new Promise((resolve, reject) => {
    requestWithTokenCheck({
      url: `${API.playStart}${deviceId}/${channelId}`,
      data: {
        isSubStream: false
      },
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      resolve(res.data);
    })
  })
}

/**
 * 设备摄像头播放
 * @param deviceId
 * @param channelId
 * @returns
 */
export const cameraGbRecordQueryApi = async (query, params) => {
  let { deviceId, channelId } = query;
  return new Promise((resolve, reject) => {
    requestWithTokenCheck({
      url: `${API.gbRecordQuery}${deviceId}/${channelId}`,
      data: params,
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      resolve(res.data);
    })
  })
}


/**
 * 设备时间段
 * @param deviceId
 * @param channelId
 * @returns
 */
export const deviceCameraDateListApi = async (params) => {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: `${API.dateList}`,
      type: 'GET',
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      },
      data: params,
      success(res) {
        if (res.code === 100) {
          message.warning(res.msg);
          reject();
        }
        resolve(res.data);
      },
      error(error) {
        console.log(error);
        reject(error);
      }
    })
  })
}

/**
 * 设备摄像头回放
 * @param deviceId
 * @param channelId
 * @returns
 */
export const cameraPlayBackStopApi = async (data) => {
  let { deviceId, channelId, streamId } = data;
  return new Promise((resolve, reject) => {
    requestWithTokenCheck({
      url: `${API.playBackStop}${deviceId}/${channelId}/${streamId}`,
      data: {},
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      resolve(res.data);
    })
  })
}

/**
 * 码流设置
 * @param deviceId
 * @param channelId
 * @returns
 */
export const cameraIdentificationUpdateApi = async (params) => {
  return new Promise((resolve, reject) => {
    requestWithTokenCheck({
      url: API.identificationUpdate,
      data: params,
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      resolve(res.data);
    })
  })
}

/**
 * 设备摄像头回放
 * @param deviceId
 * @param channelId
 * @returns
 */
export const cameraPlayBackApi = async (data, params) => {
  let { deviceId, channelId } = data;
  return new Promise((resolve, reject) => {
    requestWithTokenCheck({
      url: `${API.playBack}${deviceId}/${channelId}`,
      data: params,
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      }
    }).then((res) => {
      resolve(res.data);
    })
  })
}

/**
 * 设备摄像头回放
 * @param deviceId
 * @param channelId
 * @returns
 */
export const deviceCameraStopPlayApi = async (data) => {
  let { deviceId, channelId, streamId } = data;
  return new Promise((resolve, reject) => {
    $.ajax({
      url: `${API.playStop}${deviceId}/${channelId}`,
      type: 'GET',
      headers: {
        'Access-Token': localStorage.getItem('water-camera-token'),
        'Content-Type': 'application/json'
      },
      data: {
        isSubStream: false,
      },
      success(res) {
        if (res.code === 100) {
          message.warning(res.msg);
          reject();
        }
        resolve(res.data);
      },
      error(error) {
        console.log(error);
        reject(error);
      }
    })
  })
}

// const loginTime = getCameraInfo()?.dateTime;

// let now = moment().valueOf();
// let overtime = moment(loginTime).add(5, 'hours').valueOf()

// if (now > overtime) {
//   cameraSystemLogin({
//     username: 'admin',
//     password: encryptByMd5('admin'),
//   });
// }

export default {
  devicesApi: API.devices,
  treeApi: API.tree,
}